<template>
  <div class="ZYF-realtime">
    <div class="content-box">
      <div class="content-top">
        <ul class="statuslist">
          <li class="statusitem zhengchang" @click="statusSubmit('N')">正常: <span class="numberStyle">{{ statusData.N ? statusData.N : 0 }}</span>
          </li>
          <li class="statusitem chaobiao" @click="statusSubmit('E')">超标: <span class="numberStyle">{{ statusData.E ? statusData.E : 0 }}</span></li>
          <li class="statusitem guzhang" @click="statusSubmit('D')">故障: <span class="numberStyle">{{ statusData.D ? statusData.D : 0 }}</span></li>
          <li class="statusitem tingyun" @click="statusSubmit('F')">停运: <span class="numberStyle">{{ statusData.F ? statusData.F : 0 }}</span></li>
          <li class="statusitem zhongduan" @click="statusSubmit('B')">中断: <span class="numberStyle">{{ statusData.B ? statusData.B : 0 }}</span></li>
          <li class="statusitem total" @click="statusSubmit('')">全部:&nbsp;<span class="numberStyle">{{ statusData.Z }}</span></li>
          <li style="flex: 1;display: flex;justify-content: flex-end;">
            <a-form-model :model="enterpriseForm" layout="inline" :colon="false">
              <a-form-model-item label="服务部">
                <a-select v-model="enterpriseForm.areaId" show-search :filter-option="filterOption" style="width: 12vw" placeholder="请选择服务部" allowClear>
                  <a-select-option :value="v.id" v-for="v in selectData" :key="v.id">
                    {{v.name}}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="企业名称">
                <a-input v-model="enterpriseForm.companyName" placeholder="请输入企业名称" allowClear/>
              </a-form-model-item>
              <a-form-model-item style="margin: 0">
                <a-button @click="searchCompany" type="primary">搜索</a-button>
              </a-form-model-item>
            </a-form-model>
          </li>
        </ul>
      </div>
      <div class="content-center">
        <a-table :data-source="enterpriseTableData" style="width: 100%;height: 100%" :scroll="{ x: 'max-content',y: '68vh'}" :rowKey="record=> record.monitorID" size="middle"
                 :pagination="false" bordered>
          <template v-for="(v,index) in columns">
<!--            v-if="v.isshow"-->
            <a-table-column :custom-render="fn" :custom-header-cell="column=>column.ellipsis=true" :fixed="v.fixed" :key="v.title" align="center"
                            :width="v.width" :title="v.title" :data-index="v.dataIndex">
            </a-table-column>
          </template>
        </a-table>
      </div>
      <!--            弹窗-->
      <div class="pop" :class="{'animationpop':isClass,'cloanimationpop':!isClass}" ref="popref">
        <div class="header-box">
          <span style="font-size:20px;color: #1890ff">{{companyName}}</span>
          <a-icon type="close-square" class="clseicon" @click="rowclick('','')"/>
        </div>
        <div class="nav-top">
          <a-form-model :model="tableFrom" layout="inline" :colon="false">
            <a-row type="flex" justify="space-around">
              <a-col :span="10">
                <a-form-model-item label="时间分类">
                  <a-radio-group v-model="tableFrom.cn">
                    <a-radio value="2011">实时数据</a-radio>
                    <a-radio value="2051">分钟数据</a-radio>
                    <a-radio value="2061">小时数据</a-radio>
                    <a-radio value="2031">日数据</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="10">
                <a-form-model-item label="时间段">
                  <a-date-picker v-model="tableFrom.beginTime"
                                 :default-value="tableFrom.beginTime"
                                 :disabled-date="disabledStartDate" show-time
                                 format="YYYY-MM-DD HH:mm:ss" placeholder="开始时间"
                                 @openChange="handleStartOpenChange"/>
                  <span style="font-size:18px;padding:0 10px;">—</span>
                  <a-date-picker v-model="tableFrom.endTime" :default-value="tableFrom.endTime"
                                 :disabled-date="disabledEndDate" show-time
                                 format="YYYY-MM-DD HH:mm:ss" placeholder="结束时间" :open="endOpen"
                                 @openChange="handleEndOpenChange"/>
                </a-form-model-item>

              </a-col>
              <a-col :span="4" style="display: flex;justify-content: space-around;align-items: center">
                <a-button @click="exportMonth" type="primary" :loading="exportLoading">
                  月度导出
                </a-button>
                <a-button @click="searchSubmit" type="primary" style="margin: 0 10%">
                  搜索
                </a-button>
                <a-button @click="fileExport" type="primary">导出</a-button>
<!--                <a-form-model-item>-->
<!--                  -->
<!--                </a-form-model-item>-->
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <div class="body-box">
          <div class="jgtype-left">
            <a-collapse accordion :activeKey="activeKey" @change="collapseChange" destroyInactivePanel>
              <a-collapse-panel :key="item.id" :header="item.monitorName" v-for="(item,index) in ce">
                <div class="scollY">
                  <a-form-model :model="jgTypeFrom">
                    <a-checkbox-group v-model="jgTypeFrom.typecode" style="width: 100%">
                      <a-row type="flex" align="middle" v-for="(v,i) in item.monitorFactorsPos" :key="i" style="margin-bottom: 12px">
                        <a-col :span="12">
                          <a-checkbox :value="v.monitorFactorsCode">{{ v.monitorFactorsName }}</a-checkbox>
                        </a-col>
                        <a-col :span="12">
                          <a-input-number v-model="jgTypeFrom[v.monitorFactorsCode+'Min']" :min="0"
                                          :max="jgTypeFrom[v.monitorFactorsCode+'Max']?jgTypeFrom[v.monitorFactorsCode+'Max']:100"
                                          size="small"
                                          style="width: 36%"/>
                          至
                          <a-input-number v-model="jgTypeFrom[v.monitorFactorsCode+'Max']"
                                          :min="jgTypeFrom[v.monitorFactorsCode+'Min']?jgTypeFrom[v.monitorFactorsCode+'Min']:0"
                                          :max="100" size="small"
                                          style="width: 36%"/>
                        </a-col>
                      </a-row>
                    </a-checkbox-group>
                  </a-form-model>
                </div>
              </a-collapse-panel>
            </a-collapse>

          </div>
          <div class="tablechart-right">
            <div class="table-box">
              <table id="my-table" ref="Mytable">
                <thead ref="Mytablehead">
                  <tr>
                    <th class="hidden1" style="width: 200px">监测时间</th>
                    <th :style="{'width':thtdWidth}" class="hidden1" v-for="head in monitorData" :key="head.waringCode" :title="head.title+'('+head.waringCode+')'">{{head.title}}({{head.waringCode}})</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="v in TableData" :key="v.datetime">
                    <td class="hidden1" style="width: 200px">{{moment(parseInt(v.datetime)).format("YYYY/MM/DD HH:mm:ss")}}</td>
                    <td :style="{'width':thtdWidth}" class="hidden1" v-for="(factors,index) in monitorData.length" :key="index" :title="handleData(index,v.factorsDataList)">{{handleData(index,v.factorsDataList)}}</td>
                  </tr>
                </tbody>
              </table>
            </div>
<!--            <div class="clearfix" style="float: right">-->
<!--              <div class="page-box">-->
<!--                <a-pagination :show-total="total => `共${total}条记录`" v-model="pagesfrom.current" :total="pagesfrom.total"-->
<!--                              :defaultPageSize="pagesfrom.size" :item-render="itemRender" @change="pagechangeTableFn"-->
<!--                              show-size-changer :page-size-options="['20','50','100','200']" @showSizeChange="onShowSizeChange">-->
<!--                </a-pagination>-->
<!--              </div>-->
<!--            </div>-->

            <div class="switchClass"><span>曲线切换</span>
              <a-switch default-checked v-model="iszhesuan" @change="lineEcharFn"/>
            </div>
            <div class="line-echarts" ref="lineecharts"></div>
          </div>
        </div>
      </div>
<!--      弹窗完-->
      <div class="content-bottom clearfix">
        <div class="page-box">
          <a-pagination :show-total="total => `共 ${total} 条记录`" v-model="enterpriseForm.current"
                        :total="total" :defaultPageSize="enterpriseForm.size" :item-render="itemRender"
                        @change="pagechangeFn"/>
        </div>
      </div>
    </div>
    <down-loasd ref="downLoasd" :selectMN="selectMN"></down-loasd>
  </div>
</template>

<script>
import apiUrl from "@/url.config"
import moment from 'moment';
import echarts from "echarts";
import company from "@/views/components/mixin/company";
import downLoasd from "@/views/air/components/DownLoasdExcel";
let myCharts = null;
let TableDatas = [];
export default {
  mixins: [company],
  name: "index",
  inject: ["reload"],
  props: {
    monitorType: {
      type: [String, Number],
      required: true,
    }
  },
  components: {
    downLoasd, // 导出
  },
  data() {
    return {
      moment,
      thtdWidth:"200px",
      showchar: false,
      selectData:[],  //  下拉筛选数据
      // 测试
      jgTypeFrom: {
        typecode: [],
      },
      isClass: false,
      enterpriseTableData: [],
      columns: [],
      openchart: false,
      endOpen: false, // 日期组件关联弹窗
      tableFrom: {
        cn: "2011",
        mn: "",
        monitorId: "",
        beginTime: moment().add(-2, "h"),
        endTime: moment(),
        current: 1,
        size: -1,
        total:0
      },
      pagesfrom:{
        current:1,
        size:50,
        total:0
      },
      TableData: [],
      monitorData: [],
      isloading: true,
      // 测试玩
      enterpriseForm: {
        current: 1, // "long //页码",
        size: 10,//"long //条数",
        companyName: "", //"string //公司名称"
        dataStatus: "",  //"string //状态"
        areaId: undefined,  //"string //区域id"
        monitorType: "1", //"string //1废气、2废水、3水站、4空气站"
      },
      total: 0,
      carData: [],
      statusData: [],
      cloneData: [],
      ce: [],
      activeKey: "",
      IntervalName: "",
      iszhesuan: true,
      companyName:"",
      selectMN:"",  // 点击排口或数据存储mn
      exportLoading:false,
    };
  },
  methods: {
    handleData(index,list,indix1){
      let str = "";
      if(!list)return str=0;
      list.forEach(v=>{
        if(v.code === this.monitorData[index]?.waringCode){
         str = v.zsValue?v.value+" 折 "+v.zsValue:v.value;
        }
      })
      return str
    },
    // 搜索
    searchCompany(){
      this.enterpriseForm.current = 1;
      this.getListData()
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // 导出
    exportMonth(){
      let num = this.tableFrom.endTime.diff(this.tableFrom.beginTime,"d");
      if(num>30){
        this.$message.info("请选择30天以内的日期间隔！");
        return
      }
      this.exportLoading = true;
      let obj = JSON.parse(JSON.stringify(this.tableFrom));
      console.log(obj)
      obj.beginTime = new Date(obj.beginTime).getTime();
      obj.endTime = new Date(obj.endTime).getTime();
      this.$api.monitorGetMonitorHistoryDataExport(obj).then(res=>{
        if(res.data.code === 0){
          this.exportLoading = false;
          window.location.href = apiUrl.ip + res.data.data;
          console.log(res)
        }else {
          this.exportLoading = false;
          this.$message.info(res.data.errorMessage);
        }
      }).catch(err=>{
        this.exportLoading = false;
      })
    },
    fileExport() {
      this.$refs.downLoasd.isDown = true;
      this.$refs.downLoasd.id = this.activeKey;
      // this.$refs.downLoasd.init();
    },
    // 弹窗左侧
    collapseChange(key, value) {
      if (!key) {
        return
      }
      this.activeKey = key;
      this.monitorData = [];
      this.jgTypeFrom = {
        typecode: [],
      };
      for (let v=0;v<this.ce.length;v++){
        if(key === this.ce[v].id){
          this.tableFrom.mn = this.ce[v].mn;
          break;
        }
      }
      this.tableFrom.monitorId = key;

      this.ce.forEach(v => {
        if (v.id == key) {
          v.monitorFactorsPos.forEach((j) => {
            if (value) {
              this.jgTypeFrom.typecode.push(value.code)
            } else {
              this.jgTypeFrom.typecode.push(j.monitorFactorsCode)
            }

            this.jgTypeFrom[j.monitorFactorsCode + "Min"] = j.convertMin;
            this.jgTypeFrom[j.monitorFactorsCode + "Max"] = j.convertMax;
            let obj = {
              title: j.monitorFactorsName,
              unit: j.unit,
              waringCode: j.monitorFactorsCode
            };
            this.monitorData.push(obj);
          })
          console.log(this.monitorData)
          if(this.monitorData.length<=5){
            this.$refs.Mytable.style.width = "100%";
            this.thtdWidth = `${100/this.monitorData.length}%`
          }else {
            this.$refs.Mytable.style.width = `${(this.monitorData.length+1) * 200}px`;
            this.thtdWidth = "200px";
          }

          this.jgTypeFrom = {...this.jgTypeFrom};
        }
      })
      this.getMonitoringData();
    },
    // 设备状态方法
    statusSubmit(status) {
      this.enterpriseForm.current = 1;
      this.enterpriseForm.dataStatus = status;
      this.getListData()
    },
    fn(value, row) {
      const obj = {
        children: "",
        attrs: {},
      };
      const h = this.$createElement
      if (typeof value == "object") {
        if (value.name && value.type) {
          obj.children = h("div",
              {
                domProps: {
                  innerHTML: value.name,
                },
                style: {
                  cursor: "pointer",
                },
                on: {
                  click: () => {
                    this.enterpriseSubmit(row)
                  }
                }
              })
          // obj.children = value.name
          obj.attrs.rowSpan = value.rowSpan;

        } else if (value.name) {
          obj.children = value.name;
          obj.attrs.rowSpan = value.rowSpan;
        } else {
          switch (value.dataStatus) {
            case "N":
              obj.children = h("div", null, [
                h("span", {
                  domProps: {
                    innerHTML: value.convert
                  },
                  class: ["zhengchang"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                h("span", {
                  domProps: {
                    innerHTML:" 折 " + value.convertZs
                  },
                  class: [value.convertZs === false ? "hiddens" : "", "zhengchang"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                value.datetime ? h("div", null, [
                  h("a-icon", {
                    attrs: {
                      type: "clock-circle"
                    },
                    style: {
                      color: "#000",
                      fontSize: '12px',
                      paddingLeft: "4px"
                    }
                  }),
                  h("span", {
                    domProps: {
                      innerHTML: value.datetime ? moment(parseInt(value.datetime)).format("YYYY/MM/DD HH:mm:ss") : ""
                    },
                    style: {
                      color: "#000",
                      fontSize: '14px',
                      paddingLeft: "4px"
                    }
                  })
                ]):""
              ]);
              break;
            case "E":
              obj.children = h("div", null, [
                h("span", {
                  domProps: {
                    innerHTML: value.convert
                  },
                  class: ["chaobiao"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                h("span", {
                  domProps: {
                    innerHTML: " 折 " + value.convertZs
                  },
                  class: [value.convertZs === false ? "hiddens" : "", "chaobiao"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                value.datetime ? h("div", null, [
                  h("a-icon", {
                    attrs: {
                      type: "clock-circle"
                    },
                    style: {
                      color: "#000",
                      fontSize: '12px',
                      paddingLeft: "4px"
                    }
                  }),
                  h("span", {
                    domProps: {
                      innerHTML: value.datetime ? moment(parseInt(value.datetime)).format("YYYY/MM/DD HH:mm:ss") : ""
                    },
                    style: {
                      color: "#000",
                      fontSize: '14px',
                      paddingLeft: "4px"
                    }
                  })
                ]):""
              ]);
              break;
            case "F":
              obj.children = h("div", null, [
                h("span", {
                  domProps: {
                    innerHTML: value.convert
                  },
                  class: ["tingyun"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                h("span", {
                  domProps: {
                    innerHTML: " 折 " + value.convertZs
                  },
                  class: [value.convertZs === false ? "hiddens" : "", "tingyun"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                value.datetime ? h("div", null, [
                  h("a-icon", {
                    attrs: {
                      type: "clock-circle"
                    },
                    style: {
                      color: "#000",
                      fontSize: '12px',
                      paddingLeft: "4px"
                    }
                  }),
                  h("span", {
                    domProps: {
                      innerHTML: value.datetime ? moment(parseInt(value.datetime)).format("YYYY/MM/DD HH:mm:ss") : ""
                    },
                    style: {
                      color: "#000",
                      fontSize: '14px',
                      paddingLeft: "4px"
                    }
                  })
                ]):""
              ]);
              break;
            case "B":
              obj.children = h("div", null, [
                h("span", {
                  domProps: {
                    innerHTML: value.convert
                  },
                  class: ["zhongduan"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                h("span", {
                  domProps: {
                    innerHTML: " 折 " + value.convertZs
                  },
                  class: [value.convertZs === false ? "hiddens" : "", "zhongduan"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                value.datetime ? h("div", null, [
                  h("a-icon", {
                    attrs: {
                      type: "clock-circle"
                    },
                    style: {
                      color: "#000",
                      fontSize: '12px',
                      paddingLeft: "4px"
                    }
                  }),
                  h("span", {
                    domProps: {
                      innerHTML: value.datetime ? moment(parseInt(value.datetime)).format("YYYY/MM/DD HH:mm:ss") : ""
                    },
                    style: {
                      color: "#000",
                      fontSize: '14px',
                      paddingLeft: "4px"
                    }
                  })
                ]):""
              ]);
              break;
            default:
              obj.children = h("div", null, [
                h("span", {
                  domProps: {
                    innerHTML: value.convert
                  },
                  class: ["guzhang"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                h("span", {
                  domProps: {
                    innerHTML: " 折 " + value.convertZs
                  },
                  class: [value.convertZs === false ? "hiddens" : "", "guzhang"],
                  on: {
                    click: () => {
                      this.rowclick(value, row)
                    }
                  }
                }),
                value.datetime ? h("div", null, [
                  h("a-icon", {
                    attrs: {
                      type: "clock-circle"
                    },
                    style: {
                      color: "#000",
                      fontSize: '12px',
                      paddingLeft: "4px"
                    }
                  }),
                  h("span", {
                    domProps: {
                      innerHTML: value.datetime ? moment(parseInt(value.datetime)).format("YYYY/MM/DD HH:mm:ss") : ""
                    },
                    style: {
                      color: "#000",
                      fontSize: '14px',
                      paddingLeft: "4px"
                    }
                  })
                ]):""
              ]);
              // break;
          }
        }
      } else {
        obj.children = h("div",
            {
              domProps: {
                innerHTML: value,
              },
              style: {
                cursor: "pointer",
              },
              on: {
                click: () => {
                  this.rowclick(null, row)
                }
              }
            })
        // obj.children = value;
      }
      return obj;
    },
    // 点击企业
    enterpriseSubmit(data) {
      this.setDataMonitoring({id: data.companyId, companyName: data.companyName.name}, [this.monitorType])
    },
    // 点击数据弹窗
    async rowclick(value, data) {
      this.selectMN = await data.mn
      console.log(value,data)
      await this.cloneData.forEach(v => {
        if (v.companyId == data.companyId) {
          this.ce = v.monitorIdAndNamePoList;
        }
      })
      this.isClass = await !this.isClass;
      if (data) {
        this.companyName = data.companyName.name;
        document.querySelector(".pop").classList.remove("none");
        this.collapseChange(data.monitorID, value)
        this.activeKey = data.monitorID;
      } else {
        this.tableFrom = {
          cn: "2011",
          mn: "",
          monitorId: "",
          beginTime: moment().add(-2, "h"),
          endTime: moment(),
          current: 1,
          size: -1,
        };
        this.monitorData = [];
        this.TableData = [];
        this.echartsData = [];
        this.isloading = true;
        this.companyName = "";
        this.jgTypeFrom = {typecode: []};
        if(this.$httpRequestList.length>0){
          this.$httpRequestList.forEach(v=>{
            v("interrupt")
          })
        }
        this.exportLoading = false
      }

    },
    searchSubmit() {
      let num = this.tableFrom.endTime.diff(this.tableFrom.beginTime,"d");
      switch (this.tableFrom.cn){
        case "2011":
          if(num >= 3)return this.$message.info("实时数据查询间隔在3天内，请重新选择");
          break;
        case "2051":
          if(num >=15)return this.$message.info("分钟数据查询间隔在15天内，请重新选择");
          break;
        case "2061":
          num = this.tableFrom.endTime.diff(this.tableFrom.beginTime,"M");
          if(num >=3)return this.$message.info("小时数据查询间隔在3个月内，请重新选择");
          break;
        case "2031":
          num = this.tableFrom.endTime.diff(this.tableFrom.beginTime,"M");
          if(num >=12)return this.$message.info("日数据查询间隔在一年内，请重新选择");
          break;
      }
      this.getMonitoringData()
    },
    // 日期方法
    disabledStartDate(startValue) {
      const endValue = this.tableFrom.endTime;
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.tableFrom.beginTime;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    // 日期方法完
    // 分页方法
    itemRender(current, type, originalElement) {
      if (type === "prev") {
        return<a > 上一页 < /a>;
      } else if (type === "next") {
        return<a > 下一页 < /a>;
      }
      return originalElement;
    },
    pagechangeFn(page) {
      this.enterpriseForm.current = page;
      this.getListData();
    },
    pagechangeTableFn(page){
      this.pagesfrom.current = page;
      this.TableData = TableDatas.slice((page-1)*this.pagesfrom.size,page*this.pagesfrom.size)
      // this.getMonitoringData()
    },
    onShowSizeChange(current, pageSize){
      this.pagesfrom.size = pageSize;
      this.pagesfrom.current = 1;
      this.TableData = TableDatas.slice(0,1*pageSize)
    },
    // 获取分页数据
    getListData() {
      this.$api.MonitorgetMonitorRealData(this.enterpriseForm).then((res) => {
        if (res.data.code == 0) {
          let arr = []
          this.cloneData = res.data.data;
          res.data.data.forEach(v => {
            v.monitorIdAndNamePoList.forEach((j, index) => {
              let obj = {
                id: v.id,
                areaName: {
                  name: v.areaName,
                  rowSpan: index == 0 ? v.monitorIdAndNamePoList.length : 0,
                },
                companyId: v.companyId,
                companyName: {
                  name: v.companyName,
                  rowSpan: index == 0 ? v.monitorIdAndNamePoList.length : 0,
                  type: "QY",
                },
                monitorID: j.id,
                monitorName: j.monitorName,
                mn: j.mn,
                cn: j.cn
              };
              if (j.monitorFactorsPos) {
                j.monitorFactorsPos.forEach((item, index) => {
                  obj[item.monitorFactorsName] = {};
                  obj[item.monitorFactorsName].dataStatus = item.dataStatus;
                  obj[item.monitorFactorsName].convert = item.realValue;
                  obj[item.monitorFactorsName].convertZs = item.realZsValue ? item.realZsValue : false;
                  obj[item.monitorFactorsName].datetime = item.datetime;
                  obj[item.monitorFactorsName].code = item.monitorFactorsCode;
                })
              }
              arr.push(obj);
            })
          })
          // let a = "O₂含量"
          // this.enterpriseTableData[1][a].convertZs = 12;
          console.log(arr)
          this.enterpriseTableData = arr;
          this.total = res.data.total;
        } else {
          this.enterpriseTableData = [];
          this.$message.warning(
              res.data.errorMessage + "设备列表获取失败！"
          );
        }
      });
    },
    // 弹窗表格数据
    getMonitoringData() {
      this.TableData = [];
      this.echartsData = [];
      myCharts = echarts.init(this.$refs.lineecharts);
      myCharts.showLoading({
        text: "正在加载中。。。",
        maskColor: "rgba(255, 255, 255, 0.8)",
        color: "#1890ff",
        textColor: "#000",
      });
      let obj = JSON.parse(JSON.stringify(this.tableFrom));
      obj.beginTime = new Date(obj.beginTime).getTime();
      obj.endTime = new Date(obj.endTime).getTime();
      this.$api.MonitorgetMonitorHistoryData(obj).then(res => {
        if (res.data.code == 0) {
          if (res.data.data.length <= 0) {
            this.$message.info("暂无数据")
          }
          this.echartsData = JSON.parse(JSON.stringify(res.data.data));
          this.$nextTick(() => {
            this.lineEcharFn();
          })
          if (res.data.data.length > 0) {
            if(res.data.data.length>7){
              this.$refs.Mytablehead.style.paddingRight = '17px';
            }
            this.TableData = res.data.data;
            console.log(this.TableData)
          } else {
            this.TableData = [];
          }
          this.isloading = false;
        } else {
          this.$message.warning(res.data.errorMessage);
          this.lineEcharFn();
        }
      })
    },
    zhesuan(number, element) {
      let maxvalue = Math.max(...number);
      let minvalue = Math.min(...number);
      let numbers = []
      if (minvalue != maxvalue) {
        number.forEach(item => {
          item = parseInt((parseInt(element.convertMax) - parseInt(element.convertMin)) / (maxvalue - minvalue) * (item - minvalue) + parseInt(element.convertMin))
          numbers.push(item)
        })
      } else {
        number.forEach(item => {
          item = parseInt(element.convertMin)
          numbers.push(item)
        })
      }
      return numbers;
    },
    // 图表
    lineEcharFn() {
      myCharts.clear();
      let lineData = [];
      let timeData = [];
      let dataArr = [];
      this.echartsData.forEach(v => {
        timeData.push(moment(parseInt(v.datetime)).format("MM/DD HH:mm:ss"))
      })
      this.monitorData.forEach(list => {
        let obj = {
          code: list.waringCode,
          name: list.title,
          listData: [],
          zsListData:[],
          unit: list.unit,
        }
        this.echartsData.forEach((v,index) => {
          if(!v.factorsDataList){
            v.factorsDataList = this.echartsData[index-1].factorsDataList;
            v.factorsDataList.forEach(num=>{
              num.value = 0;
              num.zsValue = null;
            });
          }
          v.factorsDataList.forEach(item => {
            if (list.waringCode == item.code) {
              obj.listData.push(item.value);
              obj.zsListData.push(item.zsValue?item.value+" 折 "+item.zsValue:item.value)
            }
          })
        })
        lineData.push(obj);
      })
      console.log(this.echartsData)
      lineData.forEach(item => {
        if (this.jgTypeFrom.typecode.length > 0) {
          let ischack = this.jgTypeFrom.typecode.some(v => v == item.code);
          if (!ischack) {
            return
          }
          let element = {
            convertMax: this.jgTypeFrom[item.code + "Max"],
            convertMin: this.jgTypeFrom[item.code + "Min"],
          }
          let newobj = {
            name: item.unit ? item.name + "(" + item.unit + ")" : item.name,
            type: "line",
            //是否平滑曲线
            smooth: true,
            // 线上点的样子圆、正方形。。。
            symbol: "rect",
            // 大小
            symbolSize: 10,
            // 数据
            data: this.iszhesuan ? this.zhesuan(item.listData, element) : item.listData, element,
          }
          dataArr.push(newobj);
        }

      });
      myCharts.setOption({
        color: ["#8470ff", "#00ff7f", "#b8860b", "#EE82EE", "#AEEEEE", "#00FF7F"],
        //提示框组件
        tooltip: {
          trigger: "axis",
          show: true,
          axisPointer: {
            lineStyle: {
              color: "#1890ff",
            },
          },
          // formatter:"{b} </br> {c}"+unit
          formatter: function (params) {
            let res = "";
            for (let i = 0; i < params.length; i++) {
              let arr = [];
              lineData.forEach(item => {
                let nameUnit = item.unit ? item.name + "(" + item.unit + ")" : item.name;
                if (nameUnit == params[i].seriesName) {
                  arr = item.zsListData;
                }
              });
              res +=
                  params[i].marker +
                  params[i].seriesName + ":" +
                  arr[params[i].dataIndex] + "<br/>"
            }
            return res;
          },
        },
        grid: {
          top: 40,
          left: 40,
          bottom: "35%",
          right: 40,
        },
        xAxis: {
          name: "日期",
          nameGap: 5,
          nameTextStyle: {
            color: "#1890ff",
            fontSize: 16,
          },
          textStyle: {
            color: "red",
          },
          data: timeData,
          // min: (value) => {
          //     return Math.round(value.min);
          // },
          // axisLine: {
          //   lineStyle: {
          //     color: "#1890ff",
          //   },
          // },
          //x轴坐标的旋转
          axisLabel: {
            rotate: 45,
            color: "rgba(0,0,0,0.7)",
          },
        },
        yAxis: {
          //y轴字体颜色
          // name: unit,
          type: "value",
          nameGap: 10,
          // nameTextStyle: {
          //   color: "#1890ff",
          //   fontSize: 16,
          // },
          // axisLabel: {
          //   color: "#1890ff",
          // },
          splitLine: {
            show: true,
            //设置y轴的坐标轴刻度设置为虚线和颜色
            lineStyle: {
              type: "dashed",
              // color: "#1890ff",
            },
          },
          //y轴颜色
          // axisLine: {
          //   lineStyle: {
          //     color: "#1890ff",
          //   },
          // },
        },
        dataZoom: [
          {
            show: true,
            height: 12,
            xAxisIndex: [0],
            bottom: 0,
            start: 100,
            end: 70,
            handleIcon:
                "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
            handleSize: "110%",
            handleStyle: {
              color: "#1890ff",
            },
            textStyle: {
              color: "#1890ff",
            },
            borderColor: "#90979c",
          },
          {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 35,
          },
        ],
        series: dataArr
      });
      myCharts.hideLoading();
      window.addEventListener("resize", () => {
        myCharts.resize();
      });
    },
    initData() {
      // 获取设备各个状态数量
      this.$api.monitorGetMonitorStatus(this.monitorType).then(res => {
        if (res.data.code == 0) {
          // this.statusData = ;
          var obj = {}
          let num = 0;
          res.data.data.forEach(v => {
            num += parseInt(v.count)
            obj[v.status] = v.count;
          })
          obj.Z = num;
          this.statusData = obj
        }
      });
      // 获取表格头部警告类型
      this.$api.FindMonitorFactorsByMonitorType(this.monitorType).then(res => {
        if (res.data.code == 0) {
          let arr1 = ['ph值','cod','氨氮','总磷','总氮','流量'];
          let handleData = [];
          arr1.forEach(v=>{
            res.data.data.forEach(item=>{
              if(item.monitorFactorsName.toLocaleLowerCase().indexOf(v)>=0)handleData.push(item);
            })
          })
          handleData = new Set([...handleData,...res.data.data]);
          handleData = Array.from(handleData);
          let arr = [
            {
              title: '行政区',
              dataIndex: 'areaName',
              align: "center",
              width: 140,
              fixed: 'left',
              isshow: true,
            },
            {
              title: '企业名称',
              dataIndex: 'companyName',
              align: "center",
              width: 160,
              fixed: 'left',
              isshow: true,
            },
            {
              title: '监控点名称',
              dataIndex: 'monitorName',
              align: "center",
              width: 160,
              fixed: 'left',
              isshow: true,
            },
          ]
          handleData.forEach(v => {
            let titleObj = {
              title: v.unit ? v.monitorFactorsName + "(" + v.unit + ")" : v.monitorFactorsName,
              dataIndex: v.monitorFactorsName,
              align: "center",
              width: res.data.data.length>4?"180px":"auto",
              isshow: true,
              ellipsis:true
            }
            arr.push(titleObj)
          })
          this.columns = arr;
        }
      });
    }
  },
  created() {

  },
  mounted() {
    this.$api.areaFindPoint(3).then(res=>{
      if(res.data.code == 0){
        this.selectData = res.data.data;
      }
    })
    this.IntervalName = setInterval(()=>{
      this.initData();
      this.getListData();
    },1000*300)
    this.initData();
    this.getListData();
    document.querySelector(".pop").classList.add("none")
  },
  destroyed() {
    window.clearInterval(this.IntervalName);
  },
  watch: {
    "jgTypeFrom.typecode": {
      deep: true,
      handler() {
        this.lineEcharFn();
      }
    }
  }
};
</script>

<style scoped lang="scss">
.numberStyle{
  font-size: 24px;
}
.ZYF-realtime {
  width: 100%;
  height: 100%;
  padding: 1%;
  box-sizing: border-box;
  position: inherit;

  .none {
    display: none
  }

  .pop {
    width: 100%;
    height: 100%;
    padding: 12px;
    box-sizing: border-box;
    background: #fff;
    position: absolute;
    z-index: 2;
    bottom: 0;
    animation-duration: 1000ms;
    box-shadow: 0 0 10px 2px rgba(0,0,0,0.4);
    .header-box {
      height: 4%;
      display: flex;
      align-items: center;
    }

    .nav-top {
      height: 6%;
      width: 100%;

      ::v-deep .ant-form-item {
        margin-bottom: 0;
        display: flex;
        align-items: center;
      }

      ::v-deep .ant-form-item-children {
        //display: inline-block;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }

    .body-box {
      height: 90%;
      width: 100%;
      display: flex;

      .jgtype-left {
        width: 20%;
        height: 100%;
        ::v-deep .ant-collapse{
          height: 100%;
          overflow-y: auto;
          //&::-webkit-scrollbar {
          //  height: 12px;
          //  width: 12px;
          //  border: 1px solid #207064;
          //}
          //
          //&::-webkit-scrollbar-thumb {
          //  //border-radius: 10px;
          //  background-color: #207064;
          //}
          //
          //&::-webkit-scrollbar-track {
          //  border-radius: 0;
          //  background: transparent;
          //}
          //
          //&::-webkit-scrollbar-corner {
          //  width: 0;
          //  height: 0;
          //  background: transparent;
          //}
        }
        .scollY {
          height: 450px;
          overflow-y: auto;

          //&::-webkit-scrollbar {
          //  height: 12px;
          //  width: 12px;
          //  border: 1px solid #207064;
          //}
          //
          //&::-webkit-scrollbar-thumb {
          //  //border-radius: 10px;
          //  background-color: #207064;
          //}
          //
          //&::-webkit-scrollbar-track {
          //  border-radius: 0;
          //  background: transparent;
          //}
          //
          //&::-webkit-scrollbar-corner {
          //  width: 0;
          //  height: 0;
          //  background: transparent;
          //}
        }

        ::v-deep .ant-input-number-handler-wrap .anticon {
          color: #0fd08f;
        }

      }

      .tablechart-right {
        width: 80%;
        height: 100%;

        .table-box {
          height: 45%;
          width: 100%;
          overflow-x: auto;
          overflow-y:hidden;
          #my-table {
            height: 100%;
            text-align: center;
            min-width: 610px;
            table-layout:fixed;
            //border-color: #207064;
            border-collapse: collapse;
            border-spacing: 0;
            color: #000;
            thead {
              background-color: #fafafa;
              //color: #9fb043;
              font-size: 15px;
            }
            tr,thead,tbody { display: block; }
            td,th {

              display: inline-block;
              border-right: 1px solid #e8e8e8;
              border-bottom: 1px solid #e8e8e8;
            }
            tr {
              height: 40px;
              line-height: 40px;
              display: flex;
            }
            tbody {
              height: calc(100% - 40px);
              overflow-y: auto;
              overflow-x: hidden;
              td{
                font-size: 16px;
                //color: rgba(0, 0, 0, 0.65);
              }
            }
          }

        }

        .switchClass {
          font-size: 16px;
          display: flex;
          align-items: center;
          height: 5%;
          span {
            margin: 0 12px;
          }
        }

        .line-echarts {
          height: 50%;
          width: 100%;
        }
      }
    }

    .clseicon {
      color: #1890ff;
      font-size: 26px;
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }

  .cloanimationpop {
    opacity: 0;
    height: 0;
    animation-name: scaletransform1;
  }

  .animationpop {
    opacity: 1;
    animation-name: scaletransform;
  }

  @keyframes scaletransform {
    0% {
      height: 0;
      transform: scale(0);
      opacity: 0;
    }
    100% {
      height: 100%;
      transform: scale(1);
      opacity: 1;
    }
  }
  @keyframes scaletransform1 {
    0% {
      height: 100%;
      transform: scale(1);
      opacity: 1;
    }
    100% {
      height: 0;
      transform: scale(0);
      opacity: 0;
    }
  }

  .zhengchang {
    color: #2e9888;
    font-weight: bold;
    cursor: pointer;
  }

  .guzhang {
    color: #aa4a23;
    font-weight: bold;
    cursor: pointer;
  }

  .chaobiao {
    color: #be3636;
    font-weight: bold;
    cursor: pointer;
  }

  .zhongduan {
    color: #b67a2c;
    font-weight: bold;
    cursor: pointer;
  }

  .tingyun {
    color: #646262;
    font-weight: bold;
    cursor: pointer;
  }

  .total {
    color: #3e74b7;
    font-weight: bold;
    cursor: pointer;
  }

  .content-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .content-top {
      width: 100%;
      height: 6%;
      margin-bottom: 1%;

      .statuslist {
        height: 100%;
        display: flex;
        align-items: center;

        .statusitem {
          font-size: 16px;
          font-weight: bold;
          margin-right: 12px;
          cursor: pointer;
        }
      }
    }

    .content-center {
      width: 100%;
      height: 84%;
      .hiddens {
        display: none;
      }

      ::v-deep .ant-table-fixed-header .ant-table-scroll .ant-table-header {
        margin-bottom: 0 !important;
        overflow: hidden !important;
      }

    }

    .content-bottom {
      width: 100%;
      position: absolute;
      right: 0;
      bottom: 2px;

      .page-box {
        float: right;
        display: flex;
        align-items: center;

      }
    }
  }
}

/* 分页 */

::v-deep .ant-select-arrow{
  font-size: inherit;
}
/* 图表 */
.line-echarts {
  width: 100%;
  height: 300px;
}

.echarts-title {
  font-weight: 600;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 10px 0;
  box-sizing: border-box;
}

</style>
